<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2>系统登录</h2>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码" @keyup.enter="handleLogin">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'Login',
  components: { User, Lock },
  setup() {
    const store = useStore()
    const router = useRouter()
    const loginForm = reactive({
      username: '',
      password: ''
    })
    const loading = ref(false)
    const loginFormRef = ref(null)

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在 3 到 20 个字符之间', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur' }
      ]
    }

    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      try {
        await loginFormRef.value.validate()
        loading.value = true
        
        console.log('发送登录请求:', loginForm)
        const response = await axios.post('/api/auth/login', {
          username: loginForm.username,
          password: loginForm.password
        })
        console.log('登录响应:', response.data)

        if (response.data && response.data.code === 200 && response.data.data) {
          const { token, user } = response.data.data
          if (token && user) {
            store.dispatch('login', { token, user })
            ElMessage.success('登录成功')
            router.push('/')
          } else {
            ElMessage.error('登录失败：服务器响应格式错误')
          }
        } else {
          ElMessage.error(response.data?.message || '登录失败')
        }
      } catch (error) {
        console.error('登录错误：', error)
        if (error.response) {
          // 服务器响应错误
          const status = error.response.status
          const message = error.response.data?.message || '登录失败'
          
          switch (status) {
            case 400:
              ElMessage.error('请求参数错误：' + message)
              break
            case 401:
              ElMessage.error('用户名或密码错误')
              break
            case 403:
              ElMessage.error('没有权限访问')
              break
            case 404:
              ElMessage.error('请求的接口不存在')
              break
            case 500:
              ElMessage.error('服务器内部错误')
              break
            default:
              ElMessage.error(message)
          }
        } else if (error.request) {
          // 请求发送失败
          ElMessage.error('无法连接到服务器，请检查网络连接')
        } else {
          // 其他错误
          ElMessage.error('登录失败：' + error.message)
        }
      } finally {
        loading.value = false
      }
    }

    return {
      loginForm,
      loginFormRef,
      rules,
      loading,
      handleLogin
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
}

.login-card :deep(.el-card__header) {
  text-align: center;
  padding: 20px;
}

.login-card h2 {
  margin: 0;
  color: #303133;
}
</style> 